package cn.com.dcsgo.exception;

import cn.com.dcsgo.utils.ResponseResult;
import com.alibaba.csp.sentinel.adapter.spring.webmvc.callback.BlockExceptionHandler;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.io.Serializable;

/**
 * UserServiceBlockExceptionHandler
 * Controller层接口Sentinel限流异常处理
 *
 * @author Dcsgo
 * @since 2025/4/9 13:26
 */
@Slf4j
@Component
public class UserServiceBlockExceptionHandler implements BlockExceptionHandler {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public void handle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, BlockException e) throws Exception {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        PrintWriter writer = httpServletResponse.getWriter();
        ResponseResult<Serializable> fail = ResponseResult.fail("Web资源请求过多，请稍后再试");
        writer.write(objectMapper.writeValueAsString(fail));
        writer.flush();
        writer.close();
        log.error("UserServiceBlockExceptionHandler: {}", e.getMessage());
    }
}
